/**
 * Created by PanJiaChen on 16/11/18.
 */

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */






export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string') {
      // 使用 Date 对象解析字符串时间
      date = new Date(time)
    } else {
      // 处理其他类型的时间输入（如 number）
      date = new Date(time)
    }
  }

  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    return value.toString().padStart(2, '0')
  })
  return time_str
}






/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}


/**加密*/
import JSEncrypt from 'jsencrypt'
export function rsaPassword(pwd) {
  let encrypt = new JSEncrypt();
  encrypt.setPublicKey(
    'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApVuHULF0qx4HjXKz8GnxnLJQbIVxIRxzI7UWx2MG5agO8OpMylUZ0Wl2NuhZpyZMaeUnw1De++ZmALsxhJ0l8xqb0vACm+MqOQvWNcSmeIkqypgLAlvvW/pHOn3BQIMmL2+aiWBObhcTPftogJJKYrbN9d2prLUjV8SgrS4FMwlVb/XRuldH0hXmQc978r8OUfma6sm+Wd7jAom9cF7MDkXXUvNc/AhG9Iu3pK1pozmtHed5tqF026J/Dcr+OjLENE6Yv7J1dB/RS1eoLvRn01qiq0P0ArlQrieigh8xtrEzghl6ZKynVY3JPbMWVZswwRQzY2tTUBWQdeNg2GBb+QIDAQAB'
  );
  return encrypt.encrypt(pwd);
}


/**上传
 * e文件
 * key Object 其他字段
*/
import { getUplaodToken, getFileUrl } from '@/api/common'
import { Message, Loading } from 'element-ui'
let loadingInstance;
export async function uploadImg(file, size = 1048576, keys, type, clallback) {


  //文件后缀名
  let fileTypeName = file.name.substring(file.name.lastIndexOf('.') + 1)
  loadingInstance = Loading.service({
    text: '上传中...',
    background: 'rgba(0, 0, 0, 0.8)',
  });
  // if (file.size > size) {
  //   Message.warning(`上传图片超过${size/1024}k`)
  //   loadingInstance.close()
  //   return
  // }
  try {
    const res = await getUplaodToken({
      type: type
    })
    if (!res.status) {
      let formData = new FormData();
      for (var k in keys) {
        formData.append(k, keys[k]);
      }
      formData.append("success_action_status", "200");
      formData.append("policy", res.content.policy);
      formData.append("x-oss-signature", res.content.signature);
      formData.append("x-oss-signature-version", "OSS4-HMAC-SHA256");
      formData.append("x-oss-credential", res.content.x_oss_credential);
      formData.append("x-oss-date", res.content.x_oss_date);
      formData.append("key", res.content.dir + '/' + `${res.content.id}.${fileTypeName}`); // 文件名
      formData.append("x-oss-security-token", res.content.security_token);
      // formData.append("callback", res.content.callback);  // 添加回调参数
      formData.append("file", file); // file 必须为最后一个表单域
      fetch(res.content.host, {
        method: "POST",
        body: formData
      }).then((response) => {
        if (response.ok) {
          console.info("上传成功:", res.content.host + '/' + res.content.dir + '/' + `${res.content.id}.${fileTypeName}`);
          Message.success('上传成功')
          //url  name  id
          clallback(res.content.host + '/' + res.content.dir + '/' + `${res.content.id}.${fileTypeName}`,`${res.content.id}.${fileTypeName}`,res.content.id)
        } else {
          console.info("上传失败", response);
          Message.error('上传失败', response)
        }
      })
        .catch((error) => {
          console.error("发生错误:", error);
          Message.error('发生错误', error)
        });
    }

    loadingInstance.close()

  } catch (error) {
    loadingInstance.close()
    Message.error(error)
  }




}


// 按钮权限
import store from '@/store'
export function hasBtnAuth(str) {
  const buttonPermissions = store.getters.permissions
  // console.log(buttonPermissions,'buttonPermissions--')
  const hasPermission = buttonPermissions.find(el => el === str)
  if (!hasPermission) {
    console.warn(`权限未找到${str}`)
  }
  return hasPermission
}


// 表单配置查具体字段公用方法
export function searchFormParams(vm, params) {
  let result = vm.fromIems.find(el => el.dataIndex === params)
  if (!result) {
    console.warn('未查找到字段名：', params)
    return false
  }
  return result
}



// 检查文件类型
export function checkMediaType(url) {
  const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg'];
  const videoExtensions = ['mp4', 'avi', 'mov', 'mkv', 'flv', 'webm'];
  const extension = url.split('.').pop().toLowerCase();
  if (imageExtensions.includes(extension)) {
    return 'image';
  } else if (videoExtensions.includes(extension)) {
    return 'video';
  } else {
    return 'unknown';
  }
}




// 导入数据
export function importXlsx(file,keys,clallback) {
  const reader = new FileReader();
  var rABS = false;
  var f = file;
  FileReader.prototype.readAsBinaryString = function (f) {
    var binary = "";
    var rABS = false;
    var wb;
    var outdata;
    var reader = new FileReader();
    reader.onload = function (e) {
      var bytes = new Uint8Array(reader.result);
      var length = bytes.byteLength;
      for (var i = 0; i < length; i++) {
        binary += String.fromCharCode(bytes[i]);
      }
      var XLSX = require("xlsx");
      if (rABS) {
        wb = XLSX.read(btoa(fixdata(binary)), {
          type: "base64",
        });
      } else {
        wb = XLSX.read(binary, {
          type: "binary",
        });
      }
      outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
      let arr = [];
      // console.log(keys,)
     
      [...outdata].forEach(el=>{
        let obj = {}
        for(var k in keys){
          obj[keys[k]] = el[k]
        
        }
        arr.push(obj)
      })
      clallback(arr)
      return arr;
    };
    reader.readAsArrayBuffer(f);
  };

  if (rABS) {
    reader.readAsArrayBuffer(f);
  } else {
    reader.readAsBinaryString(f);
  }
}

